<template>
  <el-dialog
      title="图书推荐"
      v-model="visible"
      width="50%"
      :before-close="handleClose"
  >
    <div class="chat-container">
      <div class="chat-messages" ref="messagesContainer">
        <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message-bubble', message.sender]"
        >
          <div class="message-content" v-html="formatMessageContent(message.content)"></div>
          <div class="message-time">{{ message.time }}</div>
        </div>
      </div>

      <div class="input-area">
        <el-input
            v-model="userInput"
            placeholder="请输入问题..."
            @keyup.enter="sendMessage"
            clearable
        >
          <template #append>
            <el-button
                @click="sendMessage"
                :disabled="isSending"
                :loading="isSending"
            >
              {{ isSending ? '回答中...' : '发送' }}
            </el-button>
          </template>
        </el-input>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'

// 响应式数据
const userInput = ref('')
const messages = ref([])
const socket = ref(null)
const isSending = ref(false)
const currentStreamId = ref(null)
const messagesContainer = ref(null)
const visible = ref(false)

// 从父组件接收 visible 属性
const props = defineProps({
  visible: Boolean
})

// 监听 visible 属性变化
watch(() => props.visible, (newVal) => {
  visible.value = newVal
})

// 格式化消息内容
const formatMessageContent = (content) => {
  return content.replace(/\n/g, '<br>').replace(/ /g, '&nbsp;')
}

// 连接WebSocket
const connectWebSocket = () => {
  socket.value = new WebSocket('ws://localhost:8080/ws')

  socket.value.onmessage = (event) => {
    if (!event.data.trim()) return

    try {
      const response = JSON.parse(event.data)
      if (response.isEnd) {
        currentStreamId.value = null
        isSending.value = false
        return
      }

      if (response.streamId !== currentStreamId.value) {
        messages.value.push({
          content: response.content,
          sender: 'bot',
          time: getCurrentTime()
        })
        currentStreamId.value = response.streamId
      } else {
        const lastMsg = messages.value[messages.value.length - 1]
        lastMsg.content += response.content
        lastMsg.time = getCurrentTime()
      }
      nextTick(() => scrollToBottom())
    } catch (e) {
      if (event.data.includes("content")) {
        messages.value.push({
          content: event.data,
          sender: 'bot',
          time: getCurrentTime()
        })
      } else {
        console.error('解析消息失败:', e)
      }
    }
  }

  socket.value.onopen = () => console.log('WebSocket connected')
  socket.value.onerror = (error) => console.error('WebSocket error:', error)
}

// 发送消息
const sendMessage = () => {
  if (!userInput.value.trim() || isSending.value) return

  messages.value.push({
    content: userInput.value,
    sender: 'user',
    time: getCurrentTime()
  })

  isSending.value = true
  socket.value.send(JSON.stringify({
    content: userInput.value,
    streamId: Date.now()
  }))

  userInput.value = ''
  scrollToBottom()
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 获取当前时间
const getCurrentTime = () => {
  return new Date().toLocaleTimeString([], {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生命周期钩子
onMounted(connectWebSocket)
onBeforeUnmount(() => {
  if (socket.value) {
    socket.value.close()
  }
})

// 弹窗关闭处理
const handleClose = (done) => {
  visible.value = false
  done()
  emitClose()
}

// 定义 emit 事件
const emitClose = defineEmits(['close'])
</script>


<style scoped>
/* 保持原有样式不变 */
.chat-container {
  max-width: 900px;
  margin: 20px auto;
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
}

.chat-messages {
  height: 400px;
  padding: 20px;
  overflow-y: auto;
  background: #f9f9f9;
}

.message-bubble {
  margin: 10px 0;
  max-width: 100%;
  display: flex;
  flex-direction: column;
}

.message-bubble.user {
  align-self: flex-end;
  align-items: flex-end;
}

.message-bubble.bot {
  align-self: flex-start;
  align-items: flex-start;
}

.message-content {
  white-space: pre-wrap;
  word-break: break-word;
  padding: 12px 16px;
  border-radius: 15px;
  line-height: 1.4;
}

.user .message-content {
  background: #95ec69;
  border-bottom-right-radius: 3px;
}

.bot .message-content {
  background: #fff;
  border: 1px solid #eee;
  border-bottom-left-radius: 3px;
}

.message-time {
  font-size: 0.8em;
  color: #666;
  margin-top: 4px;
}

.input-area {
  padding: 20px;
  background: #fff;
  border-top: 1px solid #eee;
}

/* 调整Element Plus组件样式 */
:deep(.el-input__wrapper) {
  box-shadow: none;
  border-radius: 4px;
}

:deep(.el-input-group__append) {
  padding: 0;
  border: none;
  box-shadow: none;
}

:deep(.el-button) {
  height: 40px;
  border-radius: 0 4px 4px 0;
}

.el-button {
  width: 150px;
}
</style>
